package com.code.google.mdsc.io;

import java.io.File;

import javax.swing.SwingWorker;

import com.code.google.mdsc.gui.MainWindow;
import com.code.google.mdsc.io.log.SimpleLogger;
import com.code.google.mdsc.io.log.impl.SimpleLoggerImpl;

public abstract class AbstractTask extends SwingWorker<Void, Void> {
	private static SimpleLogger logger = SimpleLoggerImpl.getInstance();
	private final File selectedFile;

	private final MainWindow mw;

	private long startDate;
	public AbstractTask(File selectedFile, MainWindow mw) {
		if (selectedFile == null)
			throw new IllegalArgumentException("selected file must not be null");
		this.selectedFile = selectedFile;
		this.mw = mw;
	}

	protected abstract void doAfterDone();

	@Override
	protected Void doInBackground() throws Exception {
		setProgress(0);
		startDate = System.currentTimeMillis();

		doIOOperations();

		return null;
	}

	protected abstract void doIOOperations();

	@Override
	public void done() {
		doAfterDone();

		setProgress(100);

		long endDate = System.currentTimeMillis();

		long estimatedTime = (endDate - startDate) / 1000;

		logger.log(
				SimpleLogger.LogMode.DEBUG,
				("It took " + estimatedTime + "s ("
						+ Math.round(estimatedTime / 60.0) + "min) to generate the xml data"));

		showDialog();

	}

	protected MainWindow getMw() {
		return mw;
	}

	protected File getSelectedFile() {
		return selectedFile;
	}

	protected abstract void showDialog();

	public void updateProgress(int p) {
		setProgress(p);
	}

}
